﻿using ELF.Infrastructure.Data;
using Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ELF.Modules;

[DependsOn(typeof(DomainModule))]
[DependsOn(typeof(ElfDddDataModule))]
[DependsOn(typeof(ElfdddInfrastructureModule))]
public class InfrastructureModule : BaseModule
{
    public override Task ConfigureServicesAsync(IHostApplicationBuilder builder)
    {
        IConfiguration configuration = builder.Configuration;
        var services = builder.Services;

        builder.AddRedisClient(connectionName: "cache");
        services.AddMemoryCache();

        var connectionString = configuration.GetConnectionString("productDb");
        Guard.Against.Null(connectionString, message: "Connection string 'productDb' not found.");

        var version = MySqlServerVersion.LatestSupportedServerVersion; //最近版本
        if (!EF.IsDesignTime)
        {
            Console.WriteLine(version.ToString());
            version = ServerVersion.AutoDetect(connectionString);
        }

        services.AddAppDbContext<ApplicationDbContext>((sp, options) =>
        {
            options.UseMySql(connectionString, version);
        });
        services.AddScoped<DbContext, ApplicationDbContext>();

        services.AddSingleton(TimeProvider.System);

        //services.AddScoped<IIdentityService, IdentityService>();
        return base.ConfigureServicesAsync(builder);
    }
}
